﻿using System;
using DG.Tweening;
using Gp.Scripts.Data;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Gp.Scripts.GUI {
    public class LifeBarStatusIcon : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
        public BaseBuff Buff { get; set; }
        [SerializeField] private Image img;
        [SerializeField] private TMP_Text amount;
        [SerializeField] private Transform amountTextObj;
        [SerializeField] private Image cover;


        [SerializeField] private CanvasGroup detailCanvas;
        [SerializeField] private TMP_Text buffName;
        [SerializeField] private TMP_Text buffDescription;
        
        
        
        
        
        public void Render(BaseBuff buff) {
            gameObject.SetActive(true);
            Buff = buff;
            Blink();
        }


        private int _lastLevel;

        private void Update() {
            if (Buff == null) {
                gameObject.SetActive(false);
                return;
            }
            
            
            if (Buff is IAdditiveBuff {Level: > 1} ab) {
                amountTextObj.gameObject.SetActive(true);
                amount.text = ab.Level.ToString();
                if (ab.Level != _lastLevel) Blink();
                
                _lastLevel = ab.Level;
            }
            else {
                amountTextObj.gameObject.SetActive(false);
            }
            
            img.sprite = Buff.EntityConfig.Icon;
        }

        private Tween _tween;

        private void Blink() {
            cover.fillAmount = 1;


            _tween ?.Kill();
            _tween = cover.DOFillAmount(0, .4f);
        }


        private Tween _tween2;
        public void OnPointerEnter(PointerEventData eventData) {
            if (Buff == null) return;

            _tween2?.Kill();
            _tween2 = detailCanvas.DOFade(1, .1f);

            var info = Buff.OnIconRender();
            buffName.text = info.BuffName;
            buffDescription.text = info.Description;
        }

        public void OnPointerExit(PointerEventData eventData) {
            _tween2?.Kill();
            _tween2 = detailCanvas.DOFade(0, .1f);
        }
    }
}